﻿function WebApi() {
    this.getConfig = function (path, data, type) {
        //Apigateway服务地址
        var strApiGateWay = sitePath;
        //解析调用服务地址，领域名.服务名
        var List = path.split(".");
        //服务名称
        var strServer = List[0];
        //领域名称
        var strDomainName = List[1];
        //服务名称
        var strServiceName = List[2];
        //构建ajax调用对象
        var objOption = {};
        //请求地址
        var servicePath = strApiGateWay + '/' + strServer + '/' + strDomainName + '/' + strServiceName;
        objOption.type = type;
        objOption.data = data;
        objOption.url = servicePath;
        return objOption;

    };
    this.ajax = function (path, strData, callback, errcallback, type) {
        if (type == null || type == undefined || type == "") {
            type = "POST";
        } else {
            type = "GET";
        }
        if (typeof (strData) == "string") {
            // if (strData != "") {
            //     strData = JSON.parse(strData);
            // }
        } else {
            if (strData != "") {
                strData = JSON.stringify(strData);
            }
        }
        var objOption = this.getConfig(path, strData, type)
        if (typeof (callback) == "undefined" || callback == null) {
            objOption.async = false;
        } else {
            objOption.success = callback;
            objOption.async = true;
        }
        if (typeof (errcallback) != "undefined" || errcallback != null) {
            objOption.error = errcallback;
        }
        var strResult = this.ajaxEx(objOption);
        if (strResult == undefined) {
            strResult = "";
        }
        return strResult;
    };
    this.getUrl = function (path, strdata) {
        var objOption = this.getConfig(path, strdata)
        var strUrl = "";
        if (objOption != null) {
            strUrl = objOption.url;
        }
        return strUrl;
    };
    //调用微信小程序页面
    this.goMicroMessengerPage = function (url) {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {    //判断是否是微信环境
            //微信环境
            dialogBox.alert("3!");
            wx.miniProgram.getEnv(function (res) {
                if (res.miniprogram) {
                    wx.miniProgram.navigateTo({
                        url: url,
                        success: function () {
                            console.log("调用成功！")
                        },
                        fail: function () {
                            wx.showToast({
                                title: '调用小程序失败！',
                                icon: 'none'
                            })
                        }
                    });
                } else {
                    mui.toast('不在微信环境中，无法调用微信小程序！');
                }
            })
        } else {
            window.location.href = sitePath + '/html/common/login.html'
        }
    };
    this.ajaxEx = function (options) {
        options = options || {};
        options.type = (options.type || "GET").toUpperCase();
        options.dataType = options.dataType || "jsonp";
        var result = "";
        var this_ = this;
        var AjaxOptions = {
            url: options.url,
            type: options.type,
            datatype: options.dataType,
            async: options.async,
            contentType: "application/json; charset=utf-8",
            beforeSend: function (r) {
                var token = sessionStorage.getItem("_token");
                if (token != "null" && token != undefined && token != null && token != "") {
                    r.setRequestHeader("AccessToken", token);
                    r.setRequestHeader("CurrenCompanyID", page.getCompanyId());
                }
            },
            success: function (data, status) {
                if (data == "" || data == null || data == undefined) {
                    mui.toast('系统调用出错，网络错误或登录超时，请重新登陆或确认服务器是否正确开启');
                    this_.goMicroMessengerPage("pages/index/index");
                    return;
                }
                if (typeof (data) === "string") {
                    try {
                        data = JSON.parse(data);
                    } catch (e) {
                        dialogBox.showMessDialog("服务器返回数据格式不正确！");
                        return;
                    }
                }
                result = data;
                if (status == "success") {
                    options.success && options.success(data);
                } else {
                    if (options.error) {
                        options.error("{status：" + status + ",info:\"" + data + "\"}");
                    } else {
                        mui.toast("调用出现异常[状态：" + status + ",信息：" + data + "]");
                        this_.goMicroMessengerPage("pages/index/index");
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var errInfo = "系统调用出错，错误信息:URL:" + options.url + "responseText:" + XMLHttpRequest.responseText + " textStatus:" + textStatus + " errorThrown" + errorThrown;
                if (options.error) {
                    options.error(errInfo);
                } else {
                    if (errInfo.indexOf("AccessToken Expired") > -1 || errInfo.indexOf("AccessToken NULL") > -1) {
                        cookie.delCookie("_token")
                        sessionStorage.removeItem("_token");
                        mui.showLoading("程序更新重启中<br>请稍等...");
                        window.setTimeout(function () {
                            this_.goMicroMessengerPage("pages/index/index");
                        }, 2000);
                    } else {
                        mui.toast("没有权限,请联系管理员");
                    }
                }
            }
        }
        if (options.data != null) {
            AjaxOptions.data = options.data;
        }
        $.ajax(AjaxOptions);
        return result;
    };
    this.matchKeyList = function (strParm) {
        var reg = /\{(.*?)\}/g;
        var arr = strParm.match(reg);
        return arr;
    };
}

function Cookie() {
    this.setCookie = function (name, value, time) {
        var hours = 1;
        if (time != null) {
            hours = time;
        }
        var exp = new Date();
        exp.setTime(exp.getTime() + hours * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
    };
    this.getCookie = function (name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    };
    this.delCookie = function (name) {
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
    }
    this.clear = function () {
        var cookies = document.cookie.split(";");
        if (cookies.length > 0) {
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i];
                var eqPos = cookie.indexOf("=");
                var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
                document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
            }
        }
    }
}

function Session() {
    var u = navigator.userAgent;
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
    this.setSession = function (name, value, time) {
        if (isiOS || isAndroid) {
            cookie.setCookie(name, value, time);
        } else {
            var json = {
                "val": value,
                "Exp_time": time != null ? ((new Date()).getTime() + time * 60 * 60 * 1000) : null,
            };
            var s = JSON.stringify(json);
            sessionStorage.setItem(name, s);
        }
    };
    this.getSession = function (name) {
        var value = '';
        if (isiOS || isAndroid) {
            value = cookie.getCookie(name);
        } else {
            var date = new Date();
            if (sessionStorage.getItem(name) == null) {
                return null;
            }
            var json = JSON.parse(sessionStorage.getItem(name));
            if (json.Exp_time != null && json.Exp_time <= date.getTime()) {
                sessionStorage.removeItem(name);
                return null;
            }
            value = json.val;
        }
        return value;
    };
    this.clear = function () {
        sessionStorage.clear();
        cookie.clear();
    };
    this.removeSession = function (name) {
        if (isiOS || isAndroid) {
            cookie.delCookie(name);
        } else {
            sessionStorage.removeItem(name);
        }
    }

}

var webApi = new WebApi();
var cookie = new Cookie()
var session = new Session();
